package com.cn.hospital.controller.auth;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.stp.StpUtil;
import com.cn.hospital.entity.LoginUser;
import com.cn.hospital.entity.SysUser;
import com.cn.hospital.service.auth.LoginService;
import com.cn.hospital.message.Msg;
import com.cn.hospital.utils.RedisUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.concurrent.TimeUnit;


@RestController
public class LoginController {

    @Reference
    LoginService loginService;
    @Autowired
    RedisUtils redisUtils;

    /**
     * 登录
     *
     * @param loginUser
     * @return
     */
    @RequestMapping("/login")
    public Msg login(@RequestBody LoginUser loginUser) {
        return saTokenCopy(loginService.login(loginUser));
    }

    public Msg saTokenCopy(Msg msg) {
        if (msg.getCode().equals(200)) {
            Map map = (Map) msg.getData();
            if (map != null && map.size() > 0) {
                SysUser sysUser = (SysUser) map.get("user");
                StpUtil.login(sysUser.getUserId());
            }
            redisUtils.set("sa-token", StpUtil.getTokenValue(), 3600L, TimeUnit.SECONDS);
        }
        return msg;
    }

    /**
     *  Sa-Token 模拟权限
     *      分两种方法: 注解方式和方法方式
     *      无权限会抛出异常NotPermissionException/NotRoleException
     *      全局异常抓取统一返回给前端
     *      如果为 * 号则视为拥有全部权限
     *
     *      权限认证
     *          @SaCheckPermission("select")
     *          StpUtil.hasPermission(" select ");
     *      角色认证
     *          @SaCheckRole("admin")
     *          StpUtil.hasRole(" admin ");
     */
    @SaCheckPermission("insert")
    @RequestMapping("/insert")
    public Msg insert() {
        return Msg.okResult(200, "insert");
    }

    @SaCheckPermission("test")
    @RequestMapping("/test")
    public Msg test() {
        return Msg.okResult(200, "test");
    }

    @SaCheckPermission("delete")
    @RequestMapping("/delete")
    public Msg delete() {
        return Msg.okResult(200, "delete");
    }

    @SaCheckPermission("update")
    @RequestMapping("/update")
    public Msg update() {
        return Msg.okResult(200, "update");
    }

    @SaCheckPermission("select")
    @RequestMapping("/select")
    public Msg select() {
        return Msg.okResult(200, "select");
    }

    @SaCheckRole("admin")
    @RequestMapping("/admin")
    public Msg admin() {
        return Msg.okResult(200, "admin");
    }

    @SaCheckRole("user")
    @RequestMapping("/user")
    public Msg user() {
        return Msg.okResult(200, "user");
    }
}
